#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "RecieveThread.h"



MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    //组件状态初始化
    ui->localPortNum->setText("18080");

    //获取本机的IP地址,并初始化相应的控件属性和变量
    QList<QHostAddress> ipAddressesList = QNetworkInterface::allAddresses();

    // use the first non-localhost IPv4 address
    for(auto &hostInfo : ipAddressesList) {
        if(hostInfo != QHostAddress::LocalHost && hostInfo.toIPv4Address()) {
            localIP = hostInfo.toString();
            break;
        }
    }

    // 设置获取的IP到相应文本框
    ui->localIpAddress->setText(localIP);
    ui->filePath->setText(QDir::currentPath() + "/");

    saveWorkThread = new QThread;
    recieveWorkThread = new QThread;

}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::on_portSwitch_clicked()
{
    //建立UDP链接
    if( ui->portSwitch->text() == "开始传输"){
        if(ui->localIpAddress->text().isEmpty() || ui->localPortNum->text().isEmpty())
        {
            QMessageBox::information(this, "提示", "本地IP/端口号错误");
            return;
        }

        recieveHandle = new RecieveThread;
        saveHandle = new SaveThread;

        recieveHandle->dataTemp = &dataQueue;
        saveHandle->dataTemp = &dataQueue;

        while (!dataQueue.empty())
            dataQueue.pop();

        QByteArray IPAddress = ui->localIpAddress->text().toLatin1();

        auto fp = ui->filePath->text();
        auto dvSize = ui->divisionSize->text().toInt();
        auto dvFlg = ui->divisionSwitch->isChecked();
        saveHandle->udpDataSave(fp,dvFlg,dvSize);

        auto port = ui->localPortNum->text().toInt();
        auto ip = IPAddress.data();
        recieveHandle->udpDataRecieve(port, ip);

        saveWorkThread->start();
        recieveWorkThread->start();

        //组件界面修改
        ui->portSwitch->setText("停止传输");
        moduleControl(false);
    } else {
        ui->portSwitch->setText(tr("开始传输"));
        moduleControl(true);


        delete recieveHandle;
        delete saveHandle;

        recieveHandle = nullptr;
        saveHandle = nullptr;
    }
}

void MainWindow::on_pathSelectBtn_clicked()
{
    QString s = QFileDialog::getExistingDirectory(this,"选择保存路径",QDir::currentPath());
    ui->filePath->setText(s);
    ui->portSwitch->setDisabled(s.isEmpty());
}

void MainWindow::moduleControl(bool control)
{
    ui->localIpAddress->setEnabled(control);
    ui->localPortNum->setEnabled(control);
    ui->pathSelectBtn->setEnabled(control);
    ui->filePath->setEnabled(control);
    ui->divisionSize->setEnabled(control);
    ui->divisionSwitch->setEnabled(control);
}
